<template>
  <div class="ui-uploader-wrap">
    <div class="ui-uploader">
      <Upload type="drag" :action="uploadUrl" :headers="uploadHeader" :multiple="true" :webkitdirectory="true" :on-success="handleSuccess" :before-upload="handleBeforeUpload" :show-upload-list="false"
        :data="uploadData" :format="['jpg','jpeg','png']">
        <div class="ui-uploader--inner">
          <Icon type="md-cloud-upload" />
          <div class="ui-uploader--label">直接拖拽文件到虚线框内即可上传</div>
          <div class="ui-uploader--tips">（支持上传多张图片，每张图片大小不要超过 2M ）</div>
        </div>
      </Upload>
    </div>
    <Spin size="large" fix v-if="loading"></Spin>
  </div>
</template>

<script>
import Setting from '@/setting'
import util from '@/libs/util'

export default {
  name: 'UiUploaders',
  data () {
    return {
      uploadHeader: {},
      uploadUrl: `${Setting.apiBaseURL}/file/upload`,
      uploadData: {},
      loading: false,
    }
  },
  mounted () {
    this.uploadHeader['Authori-zation'] = 'Bearer ' + util.cookies.get('token')
  },
  methods: {
    handleSuccess (res, file) {
      if (res.status === 200) {
        const { data } = res
        const { name } = file
        data.img_title = name
        this.$emit('on-success', { data })
      } else {
        this.$Notice.error({ title: res.msg })
      }
      this.loading = false
    },
    handleBeforeUpload (file) {
      let self = this
      self.loading = true
      return new Promise(function (resolve, reject) {
        let filereader = new FileReader()
        filereader.onload = e => {
          let src = e.target.result
          const image = new Image()
          image.onload = function () {
            self.uploadData = {
              img_width: this.width,
              img_height: this.height,
            }
            self.$nextTick(() => {
              resolve()
            })
          }
          image.onerror = reject
          image.src = src
        }
        filereader.readAsDataURL(file)
      })
    },

  },
}
</script>
<style lang="scss">
.ui-uploader {
  .ivu-upload-select {
    display: block;
  }
  .ivu-icon {
    font-size: 48px;
  }
}
.ui-uploader--label,
.ui-uploader--tips {
  color: #999;
}
.ui-uploader--tips {
  margin-top: 6px;
}
</style>
<style lang="scss" scoped>
.ui-uploader-sorts {
  padding-bottom: 8px;
  display: flex;
  align-items: center;
  .ui-select {
    margin-left: 10px;
  }
}
.ui-uploader--inner {
  border: 1px dashed #d8d8d8;
  color: #6af;
  cursor: pointer;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 120px;
}
</style>
